package com.xbongbong.paas.help.subform;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.saas.domain.entity.ContractUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.ContractTeamEnum;
import com.xbongbong.paas.help.subform.abstracts.AbstractUserTeamTransferSubForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 合同团队es和数据库格式转化
 * @author 魏荣杰
 * @date 2020/8/21 13:43
 */
@Component
public class ContractTeamTransferSubForm extends AbstractUserTeamTransferSubForm {

    private static final Logger LOG = LoggerFactory.getLogger(ContractTeamTransferSubForm.class);


    @Override
    public PaasFormDataEntity transferTeamToFormData(UserTeamEntity userTeamEntity) {
        ContractUserEntity contractUserEntity = (ContractUserEntity) userTeamEntity;
        PaasFormDataEntity paasFormDataEntity = createPaasFormDataEntityForUserTeam(userTeamEntity);

        JSONObject teamJson = JSONObject.parseObject(JSON.toJSONString(contractUserEntity));

        JSONObject data = new JSONObject();
        ContractTeamEnum[] contractTeamEnums = ContractTeamEnum.values();
        for (ContractTeamEnum contractTeamEnum : contractTeamEnums) {
            String dbAttr = contractTeamEnum.getDbAttr();
            String dataAttr = contractTeamEnum.getDataAttr();
            Integer fieldType = contractTeamEnum.getFieldType();
            formatDataForEs(teamJson, data, dbAttr, dataAttr, fieldType);
        }
        paasFormDataEntity.setData(data);

        return paasFormDataEntity;
    }

    @Override
    public UserTeamEntity transferFormDataToTeam(PaasFormDataEntity paasFormDataEntity) {

        JSONObject data = paasFormDataEntity.getData();

        JSONObject dbData = new JSONObject();
        ContractTeamEnum[] contractTeamEnums = ContractTeamEnum.values();
        for (ContractTeamEnum contractTeamEnum : contractTeamEnums) {
            String dbAttr = contractTeamEnum.getDbAttr();
            String dataAttr = contractTeamEnum.getDataAttr();
            Integer fieldType = contractTeamEnum.getFieldType();
            formatDataForDb(data, dbData, dbAttr, dataAttr, fieldType);
        }
        ContractUserEntity contractUserEntity = JSON.parseObject(dbData.toJSONString(), ContractUserEntity.class);
        contractUserEntity.setAddTime(paasFormDataEntity.getAddTime());
        contractUserEntity.setUpdateTime(paasFormDataEntity.getUpdateTime());
        contractUserEntity.setCorpid(paasFormDataEntity.getCorpid());
        contractUserEntity.setDel(paasFormDataEntity.getDel());
        contractUserEntity.setId(paasFormDataEntity.getId());
        return contractUserEntity;
    }
}
